package com.smcdd.cdb.dbo.cdb_dbo.ui.activity;

import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.Simple;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.Statistics;
import com.smcdd.cdb.dbo.cdb_dbo.service.presenter.StatisticsPresenter;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.IStatisticsAc;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DateUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DialogUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainUdis;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 作者：Administrator on 2017/7/1 15:15
 * 邮箱：zhanghuaiha@gmail.com
 *  店铺历史数据
 */

public class StatisticsActivity extends BaseActivity<IStatisticsAc,StatisticsPresenter> implements IStatisticsAc {
    private LineChart mChart;
    private ImageView back,icon;
    private TextView title,start,end,sta_date;
    private RecyclerView top;
    private Typeface mTfRegular;
    private Typeface mTfLight;
    private TimePickerView pvTime;
    private int growth_cont,online_cont,zhangfen,shiyong;
    private static final String TAG = StatisticsActivity.class.getSimpleName();
    private String udid;

    @Override
    public void initView() {
        mChart = (LineChart) findViewById(R.id.sta_chart);
        back = (ImageView) findViewById(R.id.sta_back);
        icon = (ImageView) findViewById(R.id.sta_icon);
        title = (TextView) findViewById(R.id.sta_title);
        start = (TextView) findViewById(R.id.sta_start);
        end = (TextView) findViewById(R.id.sta_end);
        top = (RecyclerView) findViewById(R.id.sta_top);
        sta_date = (TextView) findViewById(R.id.sta_date);
        end.setText(DateUtils.getNextDay(System.currentTimeMillis(),"yyyy-MM-dd",1));
        start.setText(DateUtils.getNextDay(System.currentTimeMillis(),"yyyy-MM-dd",8));
        initTimePicker();
    }

    @Override
    public void initData() {
//        Simple scan = (Simple) getIntent().getSerializableExtra("scan");
        String name = getIntent().getStringExtra("name");
        String id = getIntent().getStringExtra("id");
        udid = ObtainUdis.getUDID(StatisticsActivity.class);
        mPresenter.loadContacts(udid,id);
        title.setText(name);
        mTfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");
        mTfLight = Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf");
        // no description text
        mChart.getDescription().setEnabled(true);

        // enable touch gestures
        mChart.setTouchEnabled(true);

        mChart.setDragDecelerationFrictionCoef(0.9f);

        // enable scaling and dragging
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);
        mChart.setDrawGridBackground(false);
        mChart.setHighlightPerDragEnabled(true);

        // if disabled, scaling can be done on x- and y-axis separately
        mChart.setPinchZoom(true);
        mChart.animateX(1000);
        // get the legend (only possible after setting data)
        Legend l = mChart.getLegend();

        // modify the legend ...
        l.setForm(Legend.LegendForm.LINE);
        l.setTypeface(mTfLight);
        l.setTextSize(11f);
        l.setTextColor(Color.BLACK);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setWordWrapEnabled(true);
//        //设置自定义的markerView
//        MPChartMarkerView markerView = new MPChartMarkerView(this, R.layout.custom_marker_view);
//        mChart.setMarker(markerView);

        //让右边的y轴消失
        mChart.getAxisRight().setEnabled(false);

    }

    @Override
    public void initListener() {
        String msg = "1、达标：\r\n0 没有达标 1已经达标\r\n" +
                "2、单台日均：\r\n计算的是选中的日期范围内，平均每天的\r\n" +
                "3、平均在线数：\r\n计算的是选中的日期范围内，平均每天的";
        start.setOnClickListener(v -> pvTime.show(v));
        end.setOnClickListener(v -> pvTime.show(v));
        icon.setOnClickListener(v -> mPresenter.Dialog("提示",msg));
        back.setOnClickListener(v -> finish());
        sta_date.setOnClickListener(v -> {
            if (top.getVisibility() == View.INVISIBLE) {
                top.setVisibility(View.VISIBLE);
            }else {
                top.setVisibility(View.INVISIBLE);
            }
        });
    }

    public void showDialog(){
        mPresenter.Dialog("单台日均："+zhangfen,"平均在线数："+shiyong);
    }

    //显示隐藏某个线条
    public void visi(int position){
        List<ILineDataSet> dataSets = mChart.getData().getDataSets();
        if (dataSets.get(position).isVisible()) {
            dataSets.get(position).setVisible(false);
        }else {
            dataSets.get(position).setVisible(true);
        }
        mChart.invalidate();
    }

    LineDataSet set1, set2, set3,set4,set5,set6;

    // 这里是初始化线条的x y值 所以这里可以自己实现根据实际数据
    public void setData(List<Statistics> data){
        if (data.size() == 0) {
            DialogUtils.TSDialog(StatisticsActivity.this,"暂无数据",true);
            return;
        }
        mChart.clear();
        mChart.setData(new LineData());
        mChart.invalidate();

        //创建涨粉线集合
        ArrayList<Entry> growth = new ArrayList<>();
        //总设备
        ArrayList<Entry> total = new ArrayList<>();
        //日均涨粉 //单台日均
        ArrayList<Entry> online = new ArrayList<>();
        //使用设备
        ArrayList<Entry> used = new ArrayList<>();
        //达标
        ArrayList<Entry> is_ok = new ArrayList<>();
        //设备使用率 平均在线数
        ArrayList<Entry> charging_rate = new ArrayList<>();


        ArrayList<Integer> growth_one = new ArrayList<>();
        ArrayList<Integer> total_one = new ArrayList<>();
        ArrayList<Integer> used_one = new ArrayList<>();
        ArrayList<Integer> max_one = new ArrayList<>();


        for (int i = 0; i < data.size(); i++) {
            growth.add(new Entry(i,Integer.parseInt(data.get(i).getGrowth_fans_num())));
            total.add(new Entry(i,Integer.parseInt(data.get(i).getTotal_charging_num())));
            used.add(new Entry(i,Integer.parseInt(data.get(i).getUsed_charging_num())));
            is_ok.add(new Entry(i,Integer.parseInt(data.get(i).getIs_ok())));

            try {
                float v = Float.parseFloat(data.get(i).getUsed_charging_num()) / Integer.parseInt(data.get(i).getTotal_charging_num());
                if (Float.isNaN(v)) {
                    charging_rate.add(new Entry(i,0));
                }else {
                    charging_rate.add(new Entry(i,v));
                }
            }catch (Exception e){
                charging_rate.add(new Entry(i,0));
            }

            try {
                float v = Float.parseFloat(data.get(i).getGrowth_fans_num()) / Integer.parseInt(data.get(i).getTotal_charging_num());
                if (Float.isNaN(v)) {
                    online.add(new Entry(i,0));
                }else {
                    online.add(new Entry(i,v));
                }
            }catch (Exception e){
                online.add(new Entry(i,0));
            }


            growth_one.add(Integer.parseInt(data.get(i).getGrowth_fans_num()));
            total_one.add(Integer.parseInt(data.get(i).getTotal_charging_num()));
            used_one.add(Integer.parseInt(data.get(i).getUsed_charging_num()));
            growth_cont += Integer.parseInt(data.get(i).getGrowth_fans_num());
            zhangfen += Integer.parseInt(data.get(i).getGrowth_fans_num());
            shiyong += Integer.parseInt(data.get(i).getUsed_charging_num());
        }

            growth_cont = growth_cont == 0 ? 0:growth_cont/data.size();
            zhangfen = zhangfen == 0 ? 0:zhangfen/data.size();
            shiyong = shiyong == 0 ? 0:shiyong/data.size();


        Integer max = Collections.max(growth_one);
        Integer max1 = Collections.max(total_one);
        Integer max3 = Collections.max(used_one);
        max_one.add(max);
        max_one.add(max1);
        max_one.add(max3);
        Integer max4 = Collections.max(max_one);

        //设置Y轴高度
        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setTypeface(mTfLight);
        leftAxis.setTextColor(ColorTemplate.getHoloBlue());
        leftAxis.setAxisMaximum(max4 % 6 != 0? max4 +1: max4);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setTextColor(Color.BLACK);
        leftAxis.setDrawGridLines(true);
        leftAxis.setGranularityEnabled(true);

        //设置X轴宽度
        XAxis bottomAxis = mChart.getXAxis();
        bottomAxis.setTypeface(mTfLight);
        bottomAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        bottomAxis.setTextColor(Color.BLACK);
        bottomAxis.setAxisMaximum(data.size() - 1);
        bottomAxis.setAxisMinimum(0);
        bottomAxis.setDrawGridLines(false);
//        bottomAxis.setDrawZeroLine(false);
        bottomAxis.setGranularityEnabled(false);
        
        


        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);
            set2 = (LineDataSet) mChart.getData().getDataSetByIndex(1);
            set3 = (LineDataSet) mChart.getData().getDataSetByIndex(2);
            set4 = (LineDataSet) mChart.getData().getDataSetByIndex(3);
            set5 = (LineDataSet) mChart.getData().getDataSetByIndex(4);
            set6 = (LineDataSet) mChart.getData().getDataSetByIndex(5);
            set1.setValues(growth);
            set2.setValues(total);
            set3.setValues(online);
            set4.setValues(used);
            set5.setValues(is_ok);
            set6.setValues(charging_rate);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        }else {
            set1 = createLineData(growth,"涨粉","#5fa1c4");
            set2 = createLineData(total,"总设备","#5f79c4");
            set3 = createLineData(online,"单台日均","#c45f5f");
            set4 = createLineData(used,"使用设备","#b25fc4");
            set5 = createLineData(is_ok,"达标","#9dc45f");
            set6 = createLineData(charging_rate,"平均在线数","#805fc487");
            // create a data object with the datasets

            LineData datas = new LineData(set1, set2, set3,set4,set5,set6);
            datas.setValueTextColor(Color.BLACK);
            datas.setValueTextSize(9f);

            // set data
            mChart.setData(datas);
            mChart.notifyDataSetChanged();

            List<Integer> list = new ArrayList<>();
            list.add(1);
            list.add(2);
            list.add(4);
            list.add(5);
            visis(list);
        }
    }

    //显示隐藏某个线条
    public void visis(List<Integer> list){
        List<ILineDataSet> dataSets = mChart.getData().getDataSets();
        for (Integer integer : list) {
            dataSets.get(integer).setVisible(false);
        }
        mChart.invalidate();
    }


    public LineDataSet createLineData(ArrayList<Entry> yVals,String name,String color){
        LineDataSet set = new LineDataSet(yVals, name);
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        set.setColor(Color.parseColor(color));
        set.setCircleColor(Color.BLACK);
        set.setLineWidth(2f);
        set.setCircleRadius(2f);
        set.setFillAlpha(65);
        set.setFillColor(Color.parseColor(color));
        //每一条曲线里面点击点会出现的线条
        set.setHighLightColor(Color.parseColor("#60ffffff"));
        set.setHighlightLineWidth(1f);
        set.setDrawVerticalHighlightIndicator(true);
        set.setDrawHorizontalHighlightIndicator(false);
        return set;
    }


    /**
     * 初始化时间选着器
     */
    private void initTimePicker() {

        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                long start_time = date.getTime();
                long end_time = System.currentTimeMillis();
                if (start_time > end_time) {
                    ToastUtil.showToast("选择日期不能大于当前时间");
                    return;
                }
                String time = getTime(date);
                TextView textView = (TextView) v;
                //开始时间变化
                if (textView.getId() == R.id.sta_start) {
                    long time_long = getTime_long(end.getText().toString());
                    Log.e(TAG,"start被点击了"+time_long);
                    if (start_time < time_long) {
                        mPresenter.loadNetWork(udid,time,end.getText().toString());
                    }else {
                        ToastUtil.showToast("开始时间大于结束时间");
                        return;
                    }

                }else if (textView.getId() == R.id.sta_end) {
                    long time_long = getTime_long(start.getText().toString());
                    if (time_long < start_time) {
                        mPresenter.loadNetWork(udid,start.getText().toString(),time);
                    }else {
                        ToastUtil.showToast("结束时间必须大于开始时间");
                    }
                }
                textView.setText(time);
            }
        })
                .build();
        pvTime.setDate(Calendar.getInstance());
    }
    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }


    private long getTime_long(String time){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return  format.parse(time).getTime();

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }



    @Override
    protected StatisticsPresenter createPresenter() {
        return new StatisticsPresenter(this);
    }


    @Override
    protected int provideContentViewId() {
        return R.layout.activity_statistics;
    }

    @Override
    public RecyclerView getTop() {
        return top;
    }

    @Override
    public StatisticsActivity getAc() {
        return StatisticsActivity.this;
    }

    @Override
    public TextView getStart() {
        return start;
    }

    @Override
    public TextView getEnd() {
        return end;
    }
}
